<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>店铺管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品精选管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入搜索商品精选名" v-model="queryInfo.query" clearable @clear="getcareList">
            <el-button slot="append" icon="el-icon-search" @click="getcareList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加商品精选</el-button>
        </el-col>
      </el-row>
      <el-table :data="careList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="name" label="精选名称"></el-table-column>
        <el-table-column prop="image" label="精选背景图">
          <template slot-scope="scope">
            <!-- 实现图片点击放大效果 -->
            <el-popover placement="top-start" trigger="hover">
              <img :src="scope.row.url" style="width: 150px; height: 150px" />
              <img :src="scope.row.url" slot="reference" style="width: 50px; height: 50px" />
            </el-popover>
          </template>          
        </el-table-column>
        <el-table-column prop="goods_name" label="商品"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeadById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="添加商品精选" :visible.sync="addDialogVisible" width="47%" wid :close-on-click-modal="false" @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="精选名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="精选背景图" prop="image">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleSuccess' :on-remove="handleRemove" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item label="选择商品">
          <el-select v-model="addForm.goods" multiple placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.goods_id"
              :label="item.goods_name"
              :value="item.goods_id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCare">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑商品精选" :visible.sync="editDialogVisible" width="30%" :close-on-click-modal="false" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="精选名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="精选背景图">
            <el-upload :action="uploadPath" :on-preview="handlePreview" :on-success='handleEditSuccess' :on-remove="handleEditRemove" :file-list="fileList" :headers="headerObj" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item label="选择商品">
          <el-select v-model="editForm.goods" multiple placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.goods_id"
              :label="item.goods_name"
              :value="item.goods_id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editcare">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="80%" :close-on-click-modal="false">
      <img :src="previewPath" class="preview-img" />
    </el-dialog>
    
  </div>
</template>

<script>
import { basePath,uploadPath } from '../../../.env.development'
export default {
  data() {
    return {
      basePath,
      uploadPath,      
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      careList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      adDialogVisible: false,
      previewVisible: false,
      options: [],
      previewPath: '',
      fileList: [],
      headerObj: {
        Authorization: JSON.parse(sessionStorage.getItem('userInfo')).token,
      },      
      addForm: {
        name: '',
        image: [],
        goods: []
      },
      editForm: {},
      addFormRules: {
        name: [
          { required: true, message: '请输入商品精选名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ]
      },
      editFormRules: {
        name: [
          { required: true, message: '请输入商品精选名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ]
      },
    }
  },
  created() {
    this.getcareList(),
    this.getAllGoods()
  },
  methods: {
    async getcareList() {
      const { data: res } = await this.$http.get('care/', {
        params: this.queryInfo,
      })
      // if (res.meta.status !== 200) {
      //   return this.message.error('获取商品精选列表失败')
      // }
      const xx = JSON.parse(res.data)
      console.log('商品精选列表 xx', xx)
      xx.forEach(item =>{
        console.log('商品精选列表 item', item)
        this.$set(item,'url',basePath + item.image[0].pic)
      })
      this.careList = xx
      console.log('商品精选列表 res', this.careList)
      this.total = res.total
    },
    async getAllGoods() {
      const { data: res } = await this.$http.get('all_goods_list/')
      // if (res.meta.status !== 200) {
      //   return this.message.error('获取商品精选列表失败')
      // }
      // this.careList = JSON.parse(res.data)
      console.log('getGoodsList res', res)
      this.options = res.data.goods_list
      // this.total = res.total
    },
    handlePreview(file) {
      this.previewVisible = true
      this.previewPath = file.url
      console.log('handlePreview file', file)
    },
    handleSuccess(response) {
      this.addForm.image.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleSuccess pics', this.addForm)
    },
    handleRemove(file) {
      const filePath = file.response.data.temp_path
      const i = this.addForm.image.findIndex(item => item.pic === filePath)
      console.log('handleRemove i',i)
      this.addForm.image.splice(i,1)
       console.log('handleRemove image',this.addForm.image)
    },
    handleEditSuccess(response) {
      this.editForm.image.push({'pic':response.data.temp_path, pic_id:Math.floor(Math.random () * 9000)+1000})
      console.log('handleEditSuccess pics', this.editForm)
    },
    handleEditRemove(file) {
      const filePath = file.temp_path || file.response.data.temp_path
      const i = this.editForm.image.findIndex(item => item.pic === filePath)
      console.log('handleEditRemove i',i)
      this.editForm.image.splice(i,1)
       console.log('handleEditRemove image',this.editForm.image)
    },         
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getcareList()
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getcareList()
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose() {
      this.fileList = []
      this.$refs.editFormRef.resetFields()
    },
    addCare() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('care/', this.addForm)
        if(typeof(res) === 'string'){
            return this.$message.warning(res);
        }
        // if (res.meta.status !== 201) {
        //   return this.$message.error(res.meta.msg)
        // }
        this.addDialogVisible = false
        this.getcareList()
        this.$message.success('添加商品精选成功')
      })
    },
    editcare() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`/care/${this.editForm.id}/`, {
          name: this.editForm.name,
          image: this.editForm.image,
          goods: this.editForm.goods,
        })
        // if (res.meta.status !== 200) {
        //   return this.message.error('修改商品精选失败')
        // }
        if(typeof(res) === 'string'){
          return this.$message.warning(res)
        }           
        this.editDialogVisible = false
        this.getcareList()
        this.$message.success('修改商品精选成功')
      })
    },
    async showEditDialog(id) {
      console.log('this.editForm.id', id)
      const { data: res } = await this.$http.get(`care/${id}`)
      // if (res.meta.status !== 200) {
      //   return this.message.error('查询商品精选失败')
      // }
      console.log('care edit res', res)
      if(res === '没有权限'){
        return this.$message.warning(res)
      }
      res.image.forEach(item => {
        this.fileList.push({
          name: item.pic_id,
          url: basePath + item.pic,
          temp_path: item.pic
          })
          
        })
      this.editForm = res
      this.editDialogVisible = true
    },
    removeadById(id) {
      this.$confirm('确定要删除该商品精选吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`care/${id}`)
          console.log('ad delete res', typeof(res))
          // if (res.meta.status !== 200) {
          //   return this.message.error('删除商品精选失败')
          // }
          if(res === '没有权限'){
            return this.$message.warning(res)
          }          
          this.getcareList()
          this.$message.success('删除商品精选成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    }
  },
}
</script>
<style lang="less" scoped>
.preview-img {
  width: 100%
}
.el-select .el-input{
    width: 581px;
  }
</style>
